package studio.xiaoyun.core;

import java.io.File;
import java.net.URLDecoder;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;

/**
 * 执行系统初始化工作
 */
@Component
public class SystemInit implements ApplicationListener<ContextRefreshedEvent> {
    private Logger log = LoggerFactory.getLogger(SystemInit.class);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            try {
                initPath();
                loadConfigXML();
                log.warn("系统启动!");
            } catch (Exception e) {
                log.error("系统启动时出现错误", e);
            }
        }
    }

    /**
     * 初始化路径
     */
    void initPath() throws Exception{
        //xiaoyun.root配置在web.xml中，表示系统根目录
        String basePath = System.getProperty("xiaoyun.root");
        if (basePath == null) { //如果不是以web应用的方式启动，xiaoyun.root为null
            basePath = URLDecoder.decode(getClass().getClassLoader().getResource("").getPath(), "utf-8");  //防止中文乱码
        }
        Config.setBasePath(basePath);
        Config.setUploadPath(Config.getBasePath() + "file" + File.separator + "upload" + File.separator);
        Config.setConvertPath(Config.getBasePath()+"file"+File.separator+"convert"+File.separator);
        //如果文件夹不存在，则创建
        File uploadPath = new File(Config.getUploadPath());
        if (!uploadPath.exists()) {
            uploadPath.mkdirs();
        }
        File convertPath = new File(Config.getConvertPath());
        if(!convertPath.exists()){
            convertPath.mkdirs();
        }
    }

    /**
     * 读取配置文件 Config.xml
     */
    void loadConfigXML() throws Exception {
        //Document document = this.getConfigXMLDocument();
        //XPath xpath = XPathFactory.newInstance().newXPath();
        //NodeList nodeList = (NodeList)xpath.evaluate("/root/fileConverter/htmlConverter/converter", document,XPathConstants.NODESET);
    }

    /**
     * 读取配置文件Config.xml
     * @return Document格式的xml文档
     */
    Document getConfigXMLDocument() throws Exception {
        String basePath = System.getProperty("xiaoyun.root");
        File configFile;
        if (basePath == null) {
            configFile = new File(Config.getBasePath() + "config" + File.separator + "config.xml");
            if (!configFile.exists()) {
                configFile = new File(Config.getBasePath() + "config" + File.separator + "config-test.xml");
            }
        } else {
            configFile = new File(Config.getBasePath() + "WEB-INF" + File.separator + "classes" + File.separator + "config" + File.separator + "config.xml");
        }
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.parse(configFile);
    }

}
